package cn.springcloud.fix.uaa.web.config;

import cn.springcloud.fix.uaa.web.config.adapter.MobileSecurityConfigurerAdapter;
import cn.springcloud.fix.uaa.web.config.adapter.OpenIdSecurityConfigurerAdapter;
import cn.springcloud.fix.uaa.web.config.adapter.ValidateCodeSecurityConfigurerAdapter;
import cn.springcloud.fix.uaa.web.filter.LoginProcessFilter;
import cn.springcloud.fix.uaa.web.handler.MyAuthenticationFailureHandler;
import cn.springcloud.fix.uaa.web.handler.MyLogoutHandler;
import cn.springcloud.fix.uaa.web.handler.MyLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired(required = false)
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private ValidateCodeSecurityConfigurerAdapter validateCodeSecurityConfigurerAdapter;

    @Autowired
    private OpenIdSecurityConfigurerAdapter openIdSecurityConfigurerAdapter;

    @Autowired
    private MobileSecurityConfigurerAdapter mobileSecurityConfigurerAdapter;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /**
     * 这一步的配置是必不可少的，否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .antMatchers("/users/current").authenticated()
                .antMatchers("/oauth/authorize").permitAll()
                .and()
                .formLogin()
                .loginPage("/login.html")
                // .loginPage("http://localhost:8081/api-uaa/index.html")
                .loginProcessingUrl("/login")
                .permitAll()
                .failureHandler(myAuthenticationFailureHandler)
                .and()
                .logout()
                .addLogoutHandler(new MyLogoutHandler(tokenStore))//自定义LogoutHandler
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .clearAuthentication(true)
                .and()
                .apply(validateCodeSecurityConfigurerAdapter)
                .and()
                .apply(openIdSecurityConfigurerAdapter)
                .and()
                .apply(mobileSecurityConfigurerAdapter)
                .and()
                .addFilterBefore(new LoginProcessFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
                // 解决不允许显示在iframe的问题
                .headers().frameOptions().disable().cacheControl();

        // 基于密码 等模式可以无session,不支持授权码模式
        if (authenticationEntryPoint != null) {
            http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        } else {
            // 授权码模式单独处理，需要session的支持，此模式可以支持所有oauth2的认证
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        }
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}
